package com.agileai.esb.smc.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.jaxws.spring.NamespaceHandler.SpringServerFactoryBean;

import com.agileai.domain.DataParam;
import com.agileai.esb.component.manager.LoggerManager;
import com.agileai.esb.smc.service.SoakerManage;
import com.agileai.esb.smc.servlet.SoakerDispatchServlet;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.util.CryptionUtil;
import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;

public class SMCHelper {
	
	public static SoakerManage getSoakerManage(){
		SpringServerFactoryBean serverFactoryBean = (SpringServerFactoryBean)BeanFactory.instance().getBean("SoakerManage");
		SoakerManage soakerManage = (SoakerManage)serverFactoryBean.getServiceBean();	
		return soakerManage;
	}
	
	public static boolean isActive(String appName){
		boolean result = false;
		String appListURL = "http://localhost:"+SoakerDispatchServlet.getSoakerPort()+"/SMC/manager?actionType=list";
		String appListResponse = retrieveResponse(appListURL);
		if (appListResponse != null){
			String lineSpliter = System.getProperty("line.separator");
			String[] appInfos = appListResponse.split(lineSpliter);
			for (int i=0;i < appInfos.length;i++){
				String[] appInfo = appInfos[i].split(":");
				String tempAppName = appInfo[3];
				if (appName.equals(tempAppName)){
					String appState = appInfo[1];
					if ("running".equals(appState)){
						result = true;
					}
				}
			}
		}
		return result;
	}
	
	public static String retrieveResponse(String dataURL){
		String result= "";
		StringWriter buffer = new StringWriter();
		try {
			URL url = new URL(dataURL);
			InputStream inputStream = url.openStream();
			IOUtils.copy(inputStream, buffer, "UTF-8");
			IOUtils.closeQuietly(inputStream);
			result = buffer.toString();
		} catch (Exception e) {
			LoggerManager.instance().getRootLogger().error(e.getLocalizedMessage(),e);
		}
		return result;
	}
	
	public static void executeSQLScript(DataParam replaceData) {
		Properties props = null;
		Connection conn = null;
		try {
			props = Resources
					.getResourceAsProperties("config.properties");
			String url = props.getProperty("dataSource.url");
			String driver = props.getProperty("dataSource.driverClassName");
			String username = props.getProperty("dataSource.username");
			String password = props.getProperty("dataSource.password");
			String securityKey = props.getProperty("dataSource.securityKey");
			String _password = CryptionUtil.decryption(password, securityKey);
			String catalinaBase = System.getProperty("catalina.base");
			
			String fileModelPath = catalinaBase + File.separator + "conf"
					+ File.separator + "sqls" + File.separator + "sample.sql";
			StringWriter stringWriter = new StringWriter();
			updateFile(fileModelPath, stringWriter, replaceData);

			Class.forName(driver).newInstance();
			conn = (Connection) DriverManager.getConnection(url,
					username, _password);
			ScriptRunner runner = new ScriptRunner(conn, false, false);
			StringReader stringReader = new StringReader(stringWriter.toString());
			runner.runScript(stringReader);
		} catch (Exception e) { 
			e.printStackTrace();
			LoggerManager.instance().getRootLogger().error(e.getLocalizedMessage(),e);
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}			
			} catch (Exception e) {
				e.printStackTrace();
				LoggerManager.instance().getRootLogger().error(e.getLocalizedMessage(),e);
			}
		}
	}
	
	public static void updateFile(String fileModelPath, StringWriter stringWriter,DataParam replaceData) throws IOException {
		BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileModelPath),"UTF-8"));

		String systemSep = System.getProperty("line.separator");
		StringBuffer strBuf = new StringBuffer();
		for (String tmp = null; (tmp = bufReader.readLine()) != null; tmp = null) {
			Iterator<String> iterator = replaceData.getNames();
			while (iterator.hasNext()) {
				String oldChar = iterator.next();
				String newChar = replaceData.getString(oldChar);
				if (tmp.indexOf(oldChar) != -1) {
					tmp = tmp.replaceAll(oldChar, newChar);
				}
			}
			strBuf.append(tmp);
			strBuf.append(systemSep);
		}
		bufReader.close();

		stringWriter.write(strBuf.toString());
		stringWriter.flush();
		stringWriter.close();
	}
	
}
